package com.xiaohe66.web.domain.birth.value;

import com.xiaohe66.common.util.time.ChineseDate;
import com.xiaohe66.web.integration.value.DayValue;
import com.xiaohe66.web.integration.value.MonthValue;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.time.LocalDate;

/**
 * @author xiaohe
 * @since 2023.07.12 16:28
 */
@Getter
@EqualsAndHashCode
@RequiredArgsConstructor
public class BirthdayValue {

    private final BirthdayType type;
    private final MonthValue month;
    private final DayValue day;

    public BirthdayDate nextBirthday() {

        if (type == BirthdayType.CHINESE) {

            ChineseDate current = ChineseDate.of(LocalDate.now());

            // TODO : 需要兼容润月
            boolean needNextYear = current.getMonth() > month.getValue() ||
                    (current.getMonth() == month.getValue() && current.getDay() > day.getValue());

            ChineseDate chineseDate = needNextYear ?
                    ChineseDate.of(current.getYear() + 1, month.getValue(), day.getValue()) :
                    ChineseDate.of(current.getYear(), month.getValue(), day.getValue());

            return BirthdayDate.valueOf(chineseDate);

        } else {

            LocalDate current = LocalDate.now();

            boolean needNextYear = current.getMonthValue() > month.getValue() ||
                    (current.getMonthValue() == month.getValue() && current.getDayOfMonth() > day.getValue());

            LocalDate date = needNextYear ?
                    LocalDate.of(current.getYear() + 1, month.getValue(), day.getValue()) :
                    LocalDate.of(current.getYear(), month.getValue(), day.getValue());

            return BirthdayDate.valueOf(date);
        }
    }

    public LocalDate toDate(int year) {
        if (type == BirthdayType.CHINESE) {
            ChineseDate chineseDate = ChineseDate.of(year, month.getValue(), day.getValue());
            return chineseDate.toLocalDate();

        } else {
            return LocalDate.of(year, month.getValue(), day.getValue());
        }
    }

    public static BirthdayValue valueOf(BirthdayType type, int month, int day) {
        // TODO : impl cache
        return new BirthdayValue(type, MonthValue.valueOf(month), DayValue.valueOf(day));
    }

    @Override
    public String toString() {
        return String.format("BirthdayDate(%s, %s-%s)" , type.name(), month.getValue(), day.getValue());
    }
}
